package com.yzt.loginmodule.regist;

import android.content.Intent;
import android.util.Log;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.yzt.zhuju.arouter.RouterAccount;
import com.yzt.zhuju.base.BaseActivity;
import com.yzt.loginmodule.R;
import com.yzt.p_base.utils.ToastUtil;
import com.yzt.zhuju.network.AresSubscriber;
import com.yzt.zhuju.network.biz.BizLayer;
import com.yzt.zhuju.network.entity.sysConfig.AliOSSCredentialBean;
import com.yzt.zhuju.utils.DefaultCropFileEngine;
import com.yzt.zhuju.utils.GlideImageEngine;
import com.yzt.zhuju.utils.ImageUpLoadUtils;
import com.yzt.zhuju.utils.McImageCompressEngine;
import com.yzt.zhuju.widget.widget.ImageLoadManger;

import java.util.ArrayList;

/**
 * author : bob
 * date   : 2022/12/2
 * desc   : 上传头像
 */
@Route(path = RouterAccount.ACTIVITY_REGISTER_CHOOSE_GENDER)
public class RegisterUploadAvatarActivity extends BaseActivity {

    private String avatarUrl;

    private ImageView ivUpload;

    private EditText et_name;

    private AliOSSCredentialBean aliOSSCredentialBean;

    @Override
    public int getLayoutId() {
        return R.layout.activity_upload_avatar;
    }

    @Override
    public void installViews() {

        ivUpload = findViewById(R.id.iv_upload);

        et_name = findViewById(R.id.et_name);

        TextView tvNext = findViewById(R.id.tv_next);

        tvNext.setSelected(true);

        // 返回
        findViewById(R.id.iv_back).setOnClickListener(v -> finish());

        // 上传头像
        ivUpload.setOnClickListener(v -> {
            PictureSelector.create(mActivity)
                    .openGallery(SelectMimeType.ofImage())
                    .setImageEngine(GlideImageEngine.Companion.getInstance())
                    .setCompressEngine(McImageCompressEngine.Companion.getInstance())
                    //.setCropEngine(new DefaultCropFileEngine())
                    .setMaxSelectNum(1)
                    .isDirectReturnSingle(true)
                    .isDisplayCamera(false)
                    .isOpenClickSound(false)
                    .isFastSlidingSelect(true)
                    .isPreviewFullScreenMode(true)
                    .isPreviewZoomEffect(true)
                    .isPreviewImage(true)
                    .isMaxSelectEnabledMask(true)
                   // .isGif(false)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        });

        // 立即提交
        tvNext.setOnClickListener(v -> submitData());

        getAliSign();
    }

    private void submitData() {

        if (avatarUrl == null || avatarUrl.equals("")) {
            ToastUtil.showMessage("请选设置头像");
            return;
        }

        String nickname = et_name.getText().toString();
        if (nickname.equals("")) {
            ToastUtil.showMessage("请输入昵称");
            return;
        }
        Intent intent = new Intent(this, RegisterChooseGenderActivity.class);
        intent.putExtra("extra_header", avatarUrl);
        intent.putExtra("extra_nickname", nickname);
        startActivity(intent);
    }

    /**
     * 获取 ali oss 签名信息
     */
    public void getAliSign() {
        BizLayer.getInstance().getSystemModule().getAliSign(new AresSubscriber<AliOSSCredentialBean>() {
            @Override
            protected void onSuccess(AliOSSCredentialBean data) {
                aliOSSCredentialBean = data;
                ImageUpLoadUtils.getInstance().init(RegisterUploadAvatarActivity.this, aliOSSCredentialBean);
                Log.e("", "TeacherRegisterPresenterImpl-->我获得了ali签名信息");
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        //选择头像回调，然后将头像上传到服务端

        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            if (data != null) {

                ArrayList<LocalMedia> result = PictureSelector.obtainSelectorList(data);
                String picturePath = result.get(0).getRealPath();

                if (aliOSSCredentialBean == null) {
                    runOnUiThread(() -> {
                        showToast("获取照片签名异常，请重新选择照片");
                        getAliSign();
                    });
                } else {

                    showMProgress();

                    ImageLoadManger.loadIv(mActivity, picturePath, ivUpload);

                    String time = System.currentTimeMillis() + ".png";

                    ImageUpLoadUtils.getInstance().asyncUpLoad(time, picturePath, new ImageUpLoadUtils.OnAsyncUpLoadListener() {

                        @Override
                        public void onProgress(PutObjectRequest request, long currentSize, long totalSize) {

                        }

                        @Override
                        public void onSuccess(PutObjectRequest request, PutObjectResult result, String directory) {
                            closeProgress();
                            avatarUrl = directory + request.getObjectKey();
                        }

                        @Override
                        public void onFailure(PutObjectRequest request, ClientException clientExcepion, ServiceException serviceException) {
                            showToast("上传失败");
                            closeProgress();
                        }
                    });
                }
            }
        }
    }
}